// ---------------------------------------------------------------------------- 
// Initialisation
//

var stateIsLoaded = false;
var isTitleEditing = false;
var fieldsToBeEdited = new Array();

function init() {
    if (wave && wave.isInWaveContainer()) {
	wave.setStateCallback(waveStateHasChanged);
    }
}

function initAfterStateIsloaded() {
    if (isWaveHost()) {
	// $('#add_option_tbody').show();
    }
}

// ----------------------------------------------------------------------------
// State-Update
//

function waveStateHasChanged() {
    if (!stateIsLoaded) {
	stateIsLoaded = true;
	initAfterStateIsloaded();
    }

    try {
	setTitleFromState();

	createModelFromState();
	synchroniseViewWithModel();

	synchroniseVisibleOptionRowCaptions();

	checkToggleLock();
    } catch (err) {
	if (err != 'Removed old votes') {
	    throw err;
	}
    } finally {
	gadgets.window.adjustHeight();
    }
}

function toggleLock() {
    if (!isWaveHost()) {
	return;
    }

    var state = wave.getState();
    var isLocked = state.get('locked', 0);
    state.submitValue('locked', (1 - isLocked));
}

function checkToggleLock() {
    var state = wave.getState();
    var isLocked = (state.get('locked', 0) == 1);

    if (isLocked) {
	if (!isWaveHost()) {
	    $("[id^='cmd_']").hide();
	    $("[id^='caption_']").removeClass('optioncanbeeditedcaption');
	    $('#add_option_tbody').hide();
	    $('#title').css('');
	} else {
	    $('#locklink').html('Unlock');
	}
    } else {
	if (!isWaveHost()) {
	    $("[id^='cmd_']").show();
	    $("[id^='caption_']").addClass('optioncanbeeditedcaption');
	    $('#add_option_tbody').show();
	    $('#title').css('cursor:pointer;');
	} else {
	    $('#locklink').html('Lock');
	}
    }
}

function setTitleFromState() {
    var state = wave.getState();
    var title = state.get('title', '');

    if (title == '' && !isTitleEditing) {
	editTitle();
    } else if (isTitleEditing) {
	var titleEditboxSelector = getIdSelector('title_edit_box');
	$(titleEditboxSelector).val(title);
    } else {
	var titleSelector = getIdSelector('title');
	$(titleSelector).html(renderTitleSpan(title));
    }
}

function synchroniseVisibleOptionRowCaptions() {
    var state = wave.getState();
    var state_keys = state.getKeys();

    for ( var key in model.options) {
	var caption = state.get(key, '');

	if (caption == '') {
	    if (document.getElementById("captionedit_" + key) == null) {
		showCaptionEditField(key);
	    }
	} else {
	    var spanSelector = getIdSelector('caption_' + key);
	    var editboxSelector = getIdSelector("captionedit_" + key);

	    var currentEditedTitle = $(editboxSelector).val();

	    if (currentEditedTitle == '') {
		hideCaptionEditField(key, caption);
	    } else {
		$(spanSelector).html(escapeHtml(caption));
		// $(editboxSelector).val(caption);
	    }
	}

    }
}

// ----------------------------------------------------------------------------
// Event-Handler
//

function addOptionRow() {
    var uniqueId = getUniqueId();
    var caption = '';
    var participantId = getWaveViewerId();
    var key = 'option' + '_' + encodeURIComponent(participantId) + '@@'
	    + uniqueId;

    var state = wave.getState();
    state.submitValue(key, caption);
}

function addVote(optionId, answer) {
    var participantId = getWaveViewerId();
    var state = wave.getState();
    var key = 'vote' + '::' + optionId + '::'
	    + encodeURIComponent(participantId);
    state.submitValue(key, answer);

    hideVoteOption(optionId);
    gadgets.window.adjustHeight();
}

function editTitle() {
    var state = wave.getState();

    var isLocked = (state.get('locked', 0) == 1);
    if (!isWaveHost() && isLocked) {
	return;
    }

    var title = state.get('title', 'Title');
    var handler = 'saveTitle();';
    var editBoxId = 'title_edit_box';

    var titleEditForm = renderSimpleEditForm(handler, editBoxId, title);

    var titleSelector = getIdSelector('title');
    $(titleSelector).html(titleEditForm);

    _focusAndSelectEditFieldWithId(editBoxId);

    isTitleEditing = true;
    gadgets.window.adjustHeight();
}

function saveTitle() {
    var titleEditboxSelector = getIdSelector('title_edit_box');
    var title = $(titleEditboxSelector).val();

    if (title != '') {
	var titleSelector = getIdSelector('title');
	$(titleSelector).html(renderTitleSpan(title));
	isTitleEditing = false;
	gadgets.window.adjustHeight();
    }

    var state = wave.getState();
    state.submitValue('title', title);
}

function editCaption(optionId) {
    var state = wave.getState();
    var isLocked = (state.get('locked', 0) == 1);
    if (!isWaveHost() && isLocked) {
	return;
    }
    
    showCaptionEditField(optionId);
    gadgets.window.adjustHeight();
}

function saveCaption(optionId) {
    var editFieldSelector = getIdSelector("captionedit_" + optionId);
    var newCaption = $(editFieldSelector).val();

    if (newCaption != '') {
	hideCaptionEditField(optionId, newCaption);
	gadgets.window.adjustHeight();
    }

    var state = wave.getState();
    state.submitValue(optionId, newCaption);

    focusNextEditFieldIfAny(optionId);
}

function focusNextEditFieldIfAny(optionId) {
    var sortedIds = new Array();

    for ( var currentId in model.options) {
	sortedIds.push(currentId);
    }

    sortedIds.sort();

    for ( var idx in sortedIds) {
	var currId = sortedIds[idx];
	if (currId <= optionId) {
	    continue;
	}
	var currentField = document.getElementById("captionedit_" + currId);
	if (currentField != null) {
	    currentField.focus();
	    break;
	}
    }
}

function copyOption(optionId) {
    var children = getChildenSorted(optionId);

    var newKey;
    if (children.length == 0) {
	newKey = optionId + '.' + getUniqueId();
    } else {
	firstChild = children[0];
	// also count the dot!
	var prefixLength = optionId.length + 1;
	var childPostFix = firstChild.substr(prefixLength);
	newKey = optionId + '.0' + childPostFix;
    }

    var caption = model.options[optionId].caption;

    fieldsToBeEdited.push(newKey);

    var state = wave.getState();
    state.submitValue(newKey, caption);
}

function getChildenSorted(optionId) {
    var childrenSorted = new Array();

    var selector = "[id^='" + optionId + ".']";
    $(selector).each(function(idx, domElement) {
	childrenSorted.push($(domElement).attr('id'));
    });

    childrenSorted.sort();

    return childrenSorted;
}

function removeOption(optionId) {
    var state = wave.getState();
    state.submitValue(optionId, null);
}

function removeVote(voteId, optionId) {
    var state = wave.getState();
    state.submitValue(voteId, null);

    hideVote(voteId);

    var optionId = extractOptionIdFromVoteId(voteId);
    showVoteOption(optionId);

}
